<template>
    <el-dialog v-model="showDialog" title="AI生成题目" width="600px">
      <el-form :model="form" label-width="100px">
        <el-form-item label="题型">
          <el-select v-model="form.type">
            <el-option label="选择题" value="选择题" />
            <el-option label="填空题" value="填空题" />
            <el-option label="判断题" value="判断题" />
            <el-option label="简答题" value="简答题" />
            <el-option label="计算题" value="计算题" />
          </el-select>
        </el-form-item>
        <el-form-item label="难度">
          <el-select v-model="form.difficulty">
            <el-option label="简单" value="简单" />
            <el-option label="中等" value="中等" />
            <el-option label="困难" value="困难" />
          </el-select>
        </el-form-item>
        <el-form-item label="分值">
          <el-input-number v-model="form.score" :min="1" :max="100" />
        </el-form-item>
        <el-form-item label="提示词">
          <el-input v-model="form.prompt" placeholder="请输入题目方向、知识点..." />
        </el-form-item>
      </el-form>
  
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleGenerate">生成</el-button>
      </template>
    </el-dialog>
  </template>
  
  <script setup>
  import { ref } from 'vue'
  import axios from 'axios'
  import { ElMessage } from 'element-plus'
  import request from '@/utils/request.js'
  
  const emit = defineEmits(['success'])
  
  const showDialog = ref(false)
  const loading = ref(false)
  
  const form = ref({
    type: '选择题',
    difficulty: '中等',
    score: 5,
    prompt: ''
  })
  
  const handleGenerate = async () => {
    if (!form.value.prompt) {
      ElMessage.warning('请输入提示词')
      return
    }
  
    loading.value = true
    try {
      const message = `题型：${form.value.type}，难度：${form.value.difficulty}，分值：${form.value.score}分，提示：${form.value.prompt}`
      const res = await request.post('/exercises/AI', null, {
        params: { message }
      })
     
      if (res.data) {
        
        emit('success', res.data)
        showDialog.value = false
      } else {
        ElMessage.error('生成失败')
      }
    } catch (e) {
      ElMessage.error('请求出错')
      console.error(e)
    } finally {
      loading.value = false
    }
  }
  
  // 父组件调用
  defineExpose({
    show: () => {
      showDialog.value = true
    }
  })
  </script>
  